/**
 * 产品详情
 * Created by KY on 2017/4/14.
 */
define(['ldfw/core', 'art', 'ldfw/ldlibs/dict', 'echarts','bscroll',
        'text!tpl/product/detail.tpl',
        'text!tpl/product/target_tab_panel.tpl',
        'comps/ajax', 'comps/session', 'ldfw/utils/format', 'ldfw/helper/formatHelper'],

    function (LDFW, art, dict, echarts, BScroll,tpl,
               productTargetTabPanelTpl,
              ajax, session) {

        const productInfoTabPanelTpl = `<div class="tab-panel_title">
                    <blockquote>
                        <span>基本信息</span>
                        <a href="{{pd_href}}"></a>
                    </blockquote>
                </div>
                <div class="tab-panel_content">
                    <div class="content-list weui-flex">
                        <div class="content-list_item weui-flex__item">
                            <span class="name">成立日期</span>
                            <span class="value">{{$imports.format('date','yyyy-MM-dd',fund_found_date)}}</span>
                        </div>
                        <div class="content-list_item weui-flex__item" style="flex-basis:60px">
                            <span class="name">备案编号</span>
                            <span class="value">{{beian_fund_no}}</span>
                        </div>
                    </div>
                    <div class="content-list weui-flex">
                        <div class="content-list_item weui-flex__item">
                            <span class="name">投资顾问</span>
                            <span class="value">{{invest_cons||'无'}}</span>
                        </div>
                        <div class="content-list_item weui-flex__item" style="flex-basis:60px">
                            <span class="name">基金托管人</span>
                            <span class="value">{{fund_trustee||'无'}}</span>
                        </div>
                    </div>
                    <div class="content-list weui-flex">
                
                        <div class="content-list_item weui-flex__item">
                            <span class="name">风险类型</span>
                            <span class="value">{{$imports.getDict('risk_level',risk_level)}}</span>
                        </div>
                        <div class="content-list_item weui-flex__item" style="flex-basis:60px">
                            {{if achi_compa_crite != 0}}
                                <span class="name">业绩比较基准</span>
                                <span class="value">{{$imports.getDict('achi_compa_crite',achi_compa_crite)}}</span>
                            {{/if}}
                        </div>
                    </div>
                </div>`
        const productNavTabPanelTpl = `
                    <table class="product-nav_table">
                        <tr>
                            <th>净值日期</th>
                            <th>净值</th>
                            <th>累计净值</th>
                            <th>
                                {{if $data.length >0}}
                                    {{if $data[0].net_input_frequency == 2}} 
                                        周增长率
                                    {{else if $data[0].net_input_frequency == 3}}
                                        月增长率
                                    {{else}}
                                        日增长率
                                    {{/if}}
                                {{else}}
                                        日增长率
                                {{/if}}
                            </th>
                        </tr>
                        <tbody class="product-nav_table_content">
                        {{each $data nav index}}
                        <tr>
                            <td>{{nav.init_date}}</td>
                            <td>{{$imports.format('number','0.0000',nav.share_net)}}</td>
                            <td>{{$imports.format('number','0.0000',nav.share_net_total)}}</td>
                            {{if nav.pre_nav !== 0}}
                            <td>{{$imports.format('number','$.00%',(nav.share_net - nav.pre_nav)/nav.pre_nav) }}</td>
                            {{else}}
                            <td>{{$imports.format('number','$.00%',0)}}</td>
                            {{/if}}
                        </tr>
                        {{/each}}
                        </tbody>
                    </table>
                    `

        const productAnnounceTabTpl = `{{if $data.length}}
                            {{each $data data }}
                            <a class="weui-cell news-item" href="#product/news/{{data.article_no}}">
                                <span class="weui-cell__bd">{{data.official_art_title}}</span>
                                <span class="weui-cell__ft">{{$imports.format('date','yyyy-MM-dd',data.publish_date)}}</span>
                            </a>
                            {{/each}}
                            {{else}}
                            <div style="text-align:center">
                                <span>暂无公告</span>
                            </div>
                            {{/if}}`

        const productReportTabPanel =
                    `{{if $data.length}}
                        {{each $data data }}
                        <a class="weui-cell report-item" operate="view" href="/fileDownload.do?fileId={{data.attach_url}}&isMobile=1">
                            <span class="weui-cell__bd" >{{data.report_name}}</span>
                            <span class="weui-cell__ft" >{{$imports.format('date','yyyy-MM-dd',data.rpt_date)}}</span>
                        </a>
                        {{/each}}
                        {{else}}
                        <div style="text-align:center">
                            <span>暂无报告</span>
                        </div>
                    {{/if}}`

        var View = LDFW.Container.extend({
            className: 'panel',
            tpl: tpl,
            events: {
                'click .chart_btn-group a': 'loadNavData',
                'click .detail-info_btn-group a': 'loadProductInfo',
                'click [operate="buy"]': 'buyProduct',
                'infinite ':'loadMoreNav',
                'click [operate="appoint"]': 'appointProduct'
            },
            initialize: function () {
                const _this = this
                this.on('shown', function () {
                    let bs = new BScroll($('.list-warpper')[0],{
                        scrollX:true,
                        bounce:false,
                        click:true
                    })

                    this.loadInfoData()
                })
                this.on('hidden',function(){
                })
            },
            loadMoreNav:function(){
                if(this.loading) return;
                this.loading = true;
                setTimeout(function() {
                    console.log("<p> 我是新加载的内容 </p>");
                    loading = false;
                }, 1500);
            },
            setProductNo: function (pd_no) {
                this.pd_no = pd_no
            },
            loadInfoData: function () {
                const _this = this
                let data = {pd_no: this.pd_no}
                //查询产品基本信息,查询是否有持仓份额
                $.when(ajax.post('pfL.1.221', data),ajax.post('pfL.1.205',data))
                    .done(function(resp1,resp2){
                        let productInfo = resp1[0].result,
                            hasPosition = resp2[0].result && resp2[0].result.length && true
                    _this.model.set(productInfo)
                    _this.renderInfoTab(productInfo)
                    //判断产品募集状态
                        _this.$el.find('a[operate="appoint"]').removeClass('weui-btn_disabled').removeAttr('disabled').text('立即预约')
                    if (productInfo.raise_status == 1) {
                        _this.$el.find('a[operate="buy"]').removeClass('weui-btn_disabled').removeAttr('disabled').text('认购')
                    } else if (productInfo.raise_status == 3) {
                        _this.$el.find('a[operate="buy"]').removeClass('weui-btn_disabled').removeAttr('disabled').text('申购')
                    } else if (productInfo.raise_status == 2) {
                        _this.$el.find('a[operate="buy"]').addClass('weui-btn_disabled').attr('disabled', 'disabled').text('封闭中')
                    } else {
                        _this.$el.find('a[operate="buy"]').addClass('weui-btn_disabled').attr('disabled', 'disabled').text('已结束')
                        _this.$el.find('a[operate="appoint"]').addClass('weui-btn_disabled').attr('disabled', 'disabled').text('已结束')
                    }
                    //判断净值曲线可见状态
                    let showChart = false;
                    switch(productInfo.daily_net_invisible_status){
                        case '1':
                            showChart = true
                            break
                        case '2':
                            showChart = hasPosition
                            break
                        case '3':
                            showChart = false
                            break
                    }
                    _this.model.set('show_chart', showChart ? 'show_chart':'no_chart')
                    if(showChart){
                        _this.initChart()
                        _this.$el.find('.chart_btn-group > a.active').trigger('click')
                    }
                    //判断产品指标可见状态
                    let showTarget = false;
                    switch(productInfo.rpt_invisible_status){
                        case '1':
                            showTarget = true
                            break
                        case '2':
                            showTarget = hasPosition
                            break
                        case '3':
                            showTarget = false
                            break
                    }
                    _this.model.set('show_target', showTarget ? 'show_target':'no_target')
                    //提前加载
                    if(showTarget){
                        _this.loadTargetData()
                    }
                    //判断产品公告可见状态
                    let showNews = false;
                    switch(productInfo.news_invisible_status){
                        case '1':
                            showNews = true
                            break
                        case '2':
                            showNews = hasPosition
                            break
                        case '3':
                            showNews = false
                            break
                    }
                    _this.model.set('show_news', showNews ? 'show_news':'no_news')

                    //判断产品报告可见状态
                    let showReport = false;
                    switch(productInfo.report_invisible_status){
                        case '1':
                            showReport = true
                            break
                        case '2':
                            showReport = hasPosition
                            break
                        case '3':
                            showReport = false
                            break
                    }
                    _this.model.set('show_report', showReport ? 'show_report':'no_report')

                        if(co_no==1310){
                            _this.model.set('show_purchase', 'no_purchase')
                            _this.model.set('show_appoint', 'no_purchase')
                        }else{
                            //判断产品是否可以认申购
                            let showPurchase = false;
                            switch(productInfo.conctra_invisible_status){
                                case '1':
                                    showPurchase = true
                                    break
                                case '2':
                                    showPurchase = hasPosition
                                    break
                                case '3':
                                    showPurchase = false
                                    break
                            }

                            if(productInfo.raise_status == 2){
                                _this.model.set('show_purchase', 'no_purchase')
                                _this.model.set('show_appoint', 'show_purchase')
                            }else{
                                _this.model.set('show_purchase', showPurchase ? 'show_purchase':'no_purchase')
                                _this.model.set('show_appoint', showPurchase ? 'no_purchase':'show_purchase')
                            }if(productInfo.raise_status == 2){
                                _this.model.set('show_purchase', 'no_purchase')
                                _this.model.set('show_appoint', 'show_purchase')
                            }else{
                                _this.model.set('show_purchase', showPurchase ? 'show_purchase':'no_purchase')
                                _this.model.set('show_appoint', showPurchase ? 'no_purchase':'show_purchase')
                            }


                        }


                })
                ajax.post('pfL.1.202',data).success(function(resp){
                    let html = art.compile(`
                    <ul class="weui-flex product-info">
                        <li class="unitWorth">
                            <p {{if share_net > pre_nav}}class="red"{{else}}class="green"{{/if}}>{{$imports.format('number','0.0000',share_net)}}</p>
                            <p {{if share_net > pre_nav}}class="red"{{else}}class="green"{{/if}}>
                            {{if pre_nav !== 0}}
                                {{$imports.format('number','0.00%',(share_net - pre_nav)/pre_nav)}}
                            {{else}}
                                {{$imports.format('number','0.00%',0)}}
                            {{/if}}
                            </p>
                        </li>
                        <li class="weui-flex__item netStatistics">
                            <p>上个报告日净值：<span class="red">{{$imports.format('number','0.0000',pre_nav)}}</span></p>
                            <p>累&nbsp;&nbsp;&nbsp;计&nbsp;&nbsp;&nbsp;净&nbsp;&nbsp;&nbsp;值：<span class="red">{{$imports.format('number','0.0000',share_net_total)}}</span></p>
                        </li>
                    </ul>`)(resp.result[0])
                    _this.$el.find('.product-content').html(html)
                })
            },
            //加载产品指标数据（今年，去年，前年，自成立以来）
            loadTargetData:function(){
                const _this = this
                let promises = [],
                    productTargetList = []
                let curDate = new Date(),
                    beginDate = new Date(),
                    endDate = new Date()
                for(let i = 0 ; i < 4; i++){
                    if(i!==3){
                        beginDate.setYear(curDate.getFullYear()-i)
                        beginDate.setMonth(0)
                        beginDate.setDate(1)
                        endDate.setYear(curDate.getFullYear() - i)
                        endDate.setMonth(11)
                        endDate.setDate(31)
                        promises.push(new Promise((resolve,reject)=>{
                            ajax.post('rptL.3.201',{
                                pd_no:this.pd_no,
                                qry_begin_date:beginDate.format('yyyyMMdd'),
                                qry_end_date:endDate.format('yyyyMMdd'),
                                stock_code_no: 1000300
                            }).success(resp=>resolve(resp))
                        }))
                        productTargetList.push({
                            year:beginDate.getFullYear()
                        })
                    }else{
                        promises.push(new Promise((resolve,reject)=>{
                            ajax.post('rptL.3.201',{
                                pd_no:this.pd_no,
                                qry_begin_date:0,
                                qry_end_date:curDate.format('yyyyMMdd'),
                                stock_code_no: 1000300
                            }).success(resp=>resolve(resp))
                        }))
                        productTargetList.push({
                            year:'成立以来'
                        })
                    }
                }
                Promise.all(promises).then(function(xhr){
                    productTargetList[0].result = xhr[0].result[0]
                    productTargetList[1].result = xhr[1].result[0]
                    productTargetList[2].result = xhr[2].result[0]
                    productTargetList[3].result = xhr[3].result[0]
                    _this.renderTargetTab(productTargetList)
                })
            },
            //加载业绩比较基准
            loadStockData: function () {
                const _this = this
                let stock_code = this.model.get('achi_compa_crite'),
                    stockStr = dict.getDict('achi_compa_crite', stock_code),
                    stock_param = this.model.get('stock_param')
                if(stock_param){
                    ajax.post('dcL.1.5', {
                        stock_code: stock_code,
                        exch_no: 1,
                        begin_date: stock_param.begin_date,
                        end_date: stock_param.end_date
                    }).success(function (resp) {
                        let stockList = resp.result,
                            stockData = []
                        if (stockList.length > 0) {
                            let firstStockValue = stockList[0].last_price,
                                firstNetValue = _this.accumulativedData[_this.accumulativedData.length-1][1]
                            //根据xx的需求，把业绩比较基准的数据过滤下，保持和发布的净值日期一致
                            _this.productNavList.forEach(function(navItem){
                                stockList.forEach(function(item){
                                    if(navItem.init_date === item.init_date){
                                        stockData.push([new Date().fromDateAndTime(item.init_date),
                                            format('number', '0.0000', item.last_price / firstStockValue * firstNetValue)])
                                        return
                                    }
                                })
                            })
                        } else {
                            stockData = [];
                        }
                        _this.renderChart(_this.accumulativedData, stockData, stockStr)
                    })
                }else{
                    _this.renderChart(_this.accumulativedData)
                }
            },
            //查询净值
            loadNavData: function (event) {
                let _this = this,
                    queryBeginDate = new Date(),
                    target = $(event.currentTarget),
                    period = target.attr('value'),
                    data = {
                        pd_no: this.pd_no,
                        qry_end_date: new Date().format('yyyyMMdd')
                    }
                switch (period) {
                    case 'all':
                        data.qry_begin_date = 0
                        break;
                    case '12':
                        queryBeginDate.setYear(queryBeginDate.getFullYear() - 1)
                        data.qry_begin_date = queryBeginDate.format('yyyyMMdd')
                        break;
                    case '6':
                        queryBeginDate.setMonth(queryBeginDate.getMonth() - 6)
                        data.qry_begin_date = queryBeginDate.format('yyyyMMdd')
                        break;
                    case '3':
                        queryBeginDate.setMonth(queryBeginDate.getMonth() - 3)
                        data.qry_begin_date = queryBeginDate.format('yyyyMMdd')
                        break;
                }
                target.siblings('.active').removeClass('active')
                target.addClass('active')
                ajax.post('pfL.1.203', data).success(function (resp) {
                    let productNavList = resp.result,
                        accumulativedData = productNavList.map(function (item) {
                            return [new Date().fromDateAndTime(item.init_date), format('number','0.0000',item.share_net_total)]
                        })
                    _this.productNavList = productNavList
                    _this.accumulativedData = accumulativedData
                    _this.renderChart(accumulativedData)
                    if(productNavList.length){
                        _this.model.set('stock_param',{
                            'end_date':productNavList[0].init_date,
                            'begin_date':productNavList[productNavList.length-1].init_date
                        })
                        if(_this.model.has('achi_compa_crite')){
                            _this.loadStockData()
                        }else{
                            _this.model.on('change:achi_compa_crite',function(){
                                _this.loadStockData()
                            })
                        }
                    }
                })
            },
            //初始化echart
            initChart: function () {
                const chart = this.chart = echarts.init(document.getElementById('netWorth'))
                let option = this.chartOption = {
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            label: {
                                backgroundColor: '#ccc'
                            }
                        }
                    },
                    grid: {
                        top: "35px",
                        left: '10px',
                        bottom: '30px',
                        containLabel: true,//网格默认背景色透明
                        borderColor: "#3c3f47"
                    },
                    xAxis: {
                        type: 'time',
                        axisLine: {
                            show: true,
                            lineStyle: {
                                color: 'rgba(128, 128, 128, 0.5)'
                            }
                        },
                        splitLine: {
                            show: false
                        },
                        splitNumber:4,
                        axisLabel: {
                            textStyle: {
                                color: "#b3bcc5"
                            },
                            fontSize:10,
                            formatter: function (value, index) {
                                var date = new Date(value)
                                return date.format('yyyyMMdd')
                            }
                        }
                    },
                    yAxis: {
                        type: 'value',
                        axisLine: {
                            show: false
                        },
                        axisTick: {
                            show: false
                        },
                        splitLine: {
                            show: true,
                            lineStyle: {
                                color: 'rgba(128, 128, 128, 0.5)'
                            }
                        },
                        scale: true,
                        axisLabel: {   //坐标轴刻度标签
                            textStyle: {
                                color: "#b3bcc5"
                            },
                            formatter: function (value, index) {
                                return value.toFixed(4);
                            }
                        },
                        boundaryGap:['5%','5%']
                    },
                    color: ['#09c', '#f90']
                }
            },
            //渲染echart
            renderChart: function (accumulativedData, stockData, stockStr) {
                let legend, series;
                // 如果没有设置业绩比较基准，则不需要展示
                if (stockData && stockStr && stockStr!="无") {
                    legend = {
                        data: ['累计净值', stockStr],
                        top: 5
                    }
                    series = [{
                        name: '累计净值',
                        type: 'line',
                        symbol: 'circle',
                        symbolSize: 1,
                        data: accumulativedData
                    }, {
                        name: stockStr,
                        type: 'line',
                        symbol: 'circle',
                        symbolSize: 1,
                        data: stockData
                    }]
                } else {
                    legend = {
                        data: ['累计净值'],
                        top: 5
                    }
                    series = [{
                        name: '累计净值',
                        type: 'line',
                        symbol: 'circle',
                        symbolSize: 1,
                        data: accumulativedData
                    }]
                }
                this.chart.clear();
                this.chartOption.series = series;
                this.chartOption.legend = legend;
                this.chart.setOption(this.chartOption)
            },

            loadProductInfo: function (event) {
                let _this = this,
                    target = $(event.currentTarget).attr('target')
                $('.detail-info_btn-group a').removeClass('active')
                $(event.currentTarget).addClass('active')
                var li = $(event.currentTarget).parents('li')
                var left = $(li).position().left,
                    ulWidth = $('.detail-info_btn-group').width(),
                    warpperWidth = _this.$el.find('.list-warpper').width(),
                    width = $(li).width(),
                    centerLeft = (warpperWidth-width)/2
                if(left<=centerLeft){
                    $('.detail-info_btn-group').css('transform','translate(0px, 0px) translateZ(0px)')
                }else if(left - centerLeft >= ulWidth - warpperWidth){
                    $('.detail-info_btn-group').css('transform','translate('+ (warpperWidth - ulWidth) +'px, 0px) translateZ(0px)')
                }else{
                    $('.detail-info_btn-group').css('transform','translate('+ (centerLeft - left) +'px, 0px) translateZ(0px)')
                }
                this.$el.find(".weui-tab__content").each(function (index, tabcontent) {
                    $(tabcontent).hide()
                    if ($(tabcontent).attr('id') === target) {
                        $(tabcontent).show()
                    }
                })
                //产品公告
                if(target==='announce'){
                    ajax.post('pfL.13.10',{
                        pd_no: this.pd_no,
                        official_art_type:2
                    }).success(function(resp){
                        let html = art.compile(productAnnounceTabTpl)(resp.result)
                        _this.$el.find('.announce-tab_panel').find('.tab-panel_content').html(html)
                    })
                }else if(target==='nav'){
                    ajax.post('pfL.1.203',{
                        pd_no: this.pd_no,
                        qry_begin_date:0,
                        qry_end_date:new Date().format('yyyyMMdd'),
                        row_count:-1
                    }).success(function(resp){
                        let productNavList = resp.result;
                        _this.renderNavTab(productNavList)
                    })
                }else if(target==='report'){
                    ajax.post('cpliL.2.35',{
                        pd_no:this.pd_no
                    }).success(function(resp){
                        resp.result.forEach(function(item){
                            item.attach_url = item.attach_info.split(':')[0]
                        })
                        let html = art.compile(productReportTabPanel)(resp.result)
                        _this.$el.find('.report-tab_panel').find('.tab-panel_content').html(html)
                    })
                }
            },
            /**
             * 渲染产品简况 - 基本信息
             */
            renderInfoTab: function (productInfo) {
                let html = art.compile(productInfoTabPanelTpl)(productInfo)
                this.$el.find('.info-tab_panel').html(html)
            },
            /**
             * 渲染产品简况 - 主要指标
             */
            renderTargetTab(productTargetList){
                let html = art.compile(productTargetTabPanelTpl)({achi_compa_crite:this.model.get("achi_compa_crite"),data:productTargetList})
                this.$el.find('.target-tab_panel').html(html)
            },
            /**
             * 渲染产品净值
             */
            renderNavTab: function (productNavList) {
                let html = art.compile(productNavTabPanelTpl)(productNavList)
                this.$el.find('.nav-tab_panel .tab-panel_content').html(html)
                //暂时去除滚动加载
                // $('.nav-tab_panel').infinite()
                // this.navTabLoading = false;
            },

            buyProduct: function (event) {
                //新建时间戳
                const timeStamp = new Date().getTime()
                session.setItem('time_stamp',timeStamp)
                LDFW.navigate('product/approp_confirm/' + this.pd_no)
            },
            appointProduct: function (event) {
                //新建时间戳
                const timeStamp = new Date().getTime()
                session.setItem('time_stamp', timeStamp)
                LDFW.navigate('product/appoint/' + this.pd_no)
            },
        })
        return new View()
    })